package com.diannuo.springboot.configuration;

import com.alibaba.fastjson.JSON;
import org.springframework.core.MethodParameter;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpInputMessage;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.RequestBodyAdvice;

import java.io.IOException;
import java.lang.reflect.Method;
import java.lang.reflect.Type;
import java.util.Set;

@ControllerAdvice
public class RequestAdvice implements RequestBodyAdvice {

    @Override
    public boolean supports(MethodParameter methodParameter, Type targetType, Class<? extends HttpMessageConverter<?>> converterType) {
        return true;
    }

    @Override
    public HttpInputMessage beforeBodyRead(HttpInputMessage inputMessage, MethodParameter parameter, Type targetType, Class<? extends HttpMessageConverter<?>> converterType) throws IOException {
        System.out.println("beforeBodyRead开始");
        return inputMessage;
    }

    @Override
    public Object afterBodyRead(Object body, HttpInputMessage inputMessage, MethodParameter parameter, Type targetType, Class<? extends HttpMessageConverter<?>> converterType) {
        System.out.println("afterBodyRead开始");
        return body;
    }

    @Override
    public Object handleEmptyBody(Object body, HttpInputMessage inputMessage, MethodParameter parameter, Type targetType, Class<? extends HttpMessageConverter<?>> converterType) {
        return body;
    }

    private void log(Object body, HttpInputMessage inputMessage, MethodParameter parameter){
        //请求日志打印
//        Class<?> containingClass = parameter.getContainingClass();
//        Method method = parameter.getMethod();
//
//        StringBuilder sb = new StringBuilder(256);
//        sb.append("\ncontroller:").append(containingClass.getSimpleName());
//        sb.append("\nmethod:").append(method != null ? method.getName() : "null");
//        sb.append("\nparam:").append(JSON.toJSONString(body));
//        sb.append("\nheader:");
//        boolean isFirst = true;
//        HttpHeaders headers = inputMessage.getHeaders();
//        for (String key : ValueConsts.headKey) {
//            if (isFirst) {
//                isFirst = false;
//            } else {
//                sb.append("\n").append("       ");
//            }
//            sb.append(key).append(":").append(headers.get(key));
//        }
//        LogUtil.logInfo(sb.toString());
    }
}
